package com.feiwo.nonego.rpc.serialization.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.feiwo.nonego.rpc.serialization.api.Serialization;
import com.feiwo.nonego.rpc.serialization.api.exception.SerializerException;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 *
 *
 * @author feiwo 2025-08-14
 */
@SPIClass
public class KryoSerialization implements Serialization {
    @Override
    public <T> byte[] serialize(T obj) {
        if (Objects.isNull(obj)) {
            throw new SerializerException("serialization object is null");
        }

        var kryo = new Kryo();
        kryo.setReferences(false);
        kryo.register(obj.getClass(), new JavaSerializer());

        var byteArrayOutputStream = new ByteArrayOutputStream();
        var output = new Output(byteArrayOutputStream);
        kryo.writeClassAndObject(output, obj);
        output.flush();
        output.close();

        var bytes = byteArrayOutputStream.toByteArray();
        try {
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();
        } catch (IOException e) {
            throw new SerializerException(e.getMessage(),e);
        }
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        if (Objects.isNull(data)) {
            throw new SerializerException("deserialization data is null");
        }

        var kryo = new Kryo();
        kryo.setReferences(false);
        kryo.register(clazz, new JavaSerializer());

        var byteArrayInputStream = new ByteArrayInputStream(data);
        var input = new Input(byteArrayInputStream);
        //noinspection unchecked
        return (T) kryo.readClassAndObject(input);
    }
}
